package com.hilda.HTMLParserTesting.jsoup;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

public class JsoupParser {
	private static final String URL = "http://www.elandroidelibre.com";
	private Document doc = null;
	private Context mContext;

	public JsoupParser(Context c) {
		mContext = c;
		DownloadWebPageTask downloadWebPageTask = new DownloadWebPageTask();
		downloadWebPageTask.execute("web");

	}

	private boolean isSdCardAvailable() {
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			mExternalStorageWriteable = true;
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need to know is we can't write
			mExternalStorageWriteable = false;
		}

		return mExternalStorageWriteable;
	}

	private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = "";
			
				// DefaultHttpClient client = new DefaultHttpClient();
				// HttpGet httpGet = new HttpGet(url);
				// try {
				// HttpResponse execute = client.execute(httpGet);
				// InputStream content = execute.getEntity().getContent();
				//
				// BufferedReader buffer = new BufferedReader(
				// new InputStreamReader(content));
				// String s = "";
				// while ((s = buffer.readLine()) != null) {
				// response += s;
				// }
				//
				// } catch (Exception e) {
				// e.printStackTrace();
				// }

				try {
					doc = Jsoup.connect(URL).get();
				} catch (IOException e) {
					Log.e("crawDroid", e.getMessage());
				}
			
			return response;
		}

		@Override
		protected void onPostExecute(String result) {
			if (doc == null)
				return;

			String title = doc.title();

			Log.v("crawDroid", "title: " + title);

			 Log.v("crawDroid", doc.toString());

			if (!isSdCardAvailable())
				return;

			File file = new File(mContext.getExternalFilesDir(null)
					.getAbsolutePath() + "/testJsoupParser.html");
			try {
				PrintWriter out = new PrintWriter(file);
				// BufferedOutputStream bout = new BufferedOutputStream(out);
				String stringOut = doc.toString();

				out.println(stringOut);
				out.close();

			} catch (FileNotFoundException e) {
				Log.e("crawDroid", e.getMessage());
			}

			extractImages();
			extractJS();
			extractCSS();
		}
	}

	private void extractCSS() {
		Log.i("crawDroid", "extracCSS");

		Elements javascripts = doc.select("link");

		for (Element javascript : javascripts) {
			String location = javascript.attr("href");
			Log.v("crawDroid", "src atribute: " + location);

			if (!TextUtils.isEmpty(location) && location.contains("css")) {
				DownloadURL downloadURL = new DownloadURL();
				downloadURL.execute(location);
			}

		}
	}

	private void extractJS() {
		Log.i("crawDroid", "extracJS");

		Elements javascripts = doc.select("script");

		for (Element javascript : javascripts) {

			Log.v("crawDroid", "src atribute: " + javascript.attr("src"));

		}
	}

	private void extractImages() {
		Log.i("crawDroid", "extracImages");
		Elements images = doc.select("img");
		
		for (Element image : images) {
			Log.v("crawDroid", "abs:href atribute: " + image.attr("abs:href"));

			String hrefLocation = image.attr("href");
			Log.v("crawDroid", "src atribute: " + hrefLocation);
			String srcLocation = image.attr("href");
			Log.v("crawDroid", "src atribute: " + srcLocation);

//			if (!TextUtils.isEmpty(imageLocation)
//					&& imageLocation.contains("png")) {
//				DownloadURL downloadURL = new DownloadURL();
//				downloadURL.execute(imageLocation);
//			}
		}

	}

	private class DownloadURL extends AsyncTask<String, Void, String> {
		String url;

		@Override
		protected String doInBackground(String... urls) {
			String response = "";
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(URL + urls[0]);
			try {
				HttpResponse execute = client.execute(httpGet);
				InputStream content = execute.getEntity().getContent();

				BufferedReader buffer = new BufferedReader(
						new InputStreamReader(content));
				String s = "";
				while ((s = buffer.readLine()) != null) {
					response += s;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			url = urls[0];
			return response;
		}

		@Override
		protected void onPostExecute(String result) {
			if (!isSdCardAvailable())
				return;

			File file = new File(mContext.getExternalFilesDir(null)
					.getAbsolutePath() + url);

			try {
				file.getParentFile().mkdirs();
				PrintWriter out = new PrintWriter(file);
				// BufferedOutputStream bout = new BufferedOutputStream(out);
				String stringOut = doc.toString();

				out.println(stringOut);
				out.close();

			} catch (FileNotFoundException e) {
				Log.e("crawDroid", e.getMessage());
			} catch (IOException e) {
				Log.e("crawDroid", e.getMessage());
			}
		}
	}

}
